﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.ComponentModel.Composition;

namespace CodeBox.Development.Tools.RepositoryBuilder
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            DirectoryWatchingComponentCatalog cat = new DirectoryWatchingComponentCatalog();
            cat.AddDirectory(".");
            cat.AddDirectory("Extensions");
            
            CompositionContainer container = new CompositionContainer(cat.Resolver);

            string wndContract = RepositoryBuilderSettings.WindowContractName;
            ContainerControl window = null;

            var result = container.TryGetImportInfos("CodeBox.Development.Tools.RepositoryBuilderWindowContract");
            if (!result.Succeeded)
            {
                MessageBox.Show("Unable to retrieve metadata for the RepositoryBuilderWindowContract component!\nProbably components are not added into 'Extensions' folder.", "Repository Builder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            foreach (IImportInfo importInfo in result.Value)
            {
                if (wndContract.Equals((string)importInfo.Metadata[RepositoryBuilderSettings.WindowContractKeyName], StringComparison.InvariantCultureIgnoreCase))
                {
                    window = (ContainerControl)importInfo.GetBoundValue();
                }
            }

            if (typeof(Form).IsAssignableFrom(window.GetType()))
            {
                // Windows Forms
                Application.Run((Form)window);
            }
            else
            {
                // WPF
                window.Show();
            }
            
        }
    }
}
